﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Configuration;
using System.Security.Cryptography;
using System.Collections.Specialized;
using Newtonsoft.Json.Linq;
using System.Net;

/// <summary>
/// Class for Prowise SSO
/// </summary>
public class ProwiseSSO
{
    private string sharedSecret;
    private string brinNr;
    private string organisatieID;

    /// <summary>
    /// Get the needed Prowise settings from the config
    /// </summary>
    private void getProwiseSettings()
    {
        if ((brinNr = ConfigurationManager.AppSettings["ProwiseBrinnummer"]) == null)
            OmniaLogger.Log.Error("Getting ProwiseBrinnummer failed, check you web.config file");
        if ((organisatieID = ConfigurationManager.AppSettings["ProwiseOrgId"]) == null)
            OmniaLogger.Log.Error("Getting ProwiseOrgId failed, check you web.config file");
        if ((sharedSecret = ConfigurationManager.AppSettings["ProwiseBeveiligingscode"]) == null)
            OmniaLogger.Log.Error("Getting ProwiseSharedSecret failed, check you web.config file");
    }

    /// <summary>
    /// Create a token 
    /// Token is a sha hash of the date, the user and a shared secret
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    private String createTimebasedToken(string user)
    {
        try
        {
            DateTime now = DateTime.Now;
            string month = now.ToString("MM");
            string day = now.ToString("dd");

            if (String.IsNullOrEmpty(user))
                throw new Exception("username is empty");

            string hashString = day + month + user + sharedSecret;
            SHA256 sha = new SHA256CryptoServiceProvider();

            byte[] inputBytes = Encoding.UTF8.GetBytes(hashString);
            byte[] hashedBytes = sha.ComputeHash(inputBytes);

            string res = BitConverter.ToString(hashedBytes);
            string resTrimmed = res.Replace("-", "");
            return resTrimmed.ToLower();
        }
        catch (Exception ex)
        {
            OmniaLogger.Log.Error("Creating timebased toke failed: ", ex);
            return null;
        }
    }

    /// <summary>
    /// Get the needed settings
    /// </summary>
    public ProwiseSSO()
    {
        getProwiseSettings();
    }

    /// <summary>
    /// Gets the Single Sign On login url
    /// </summary>
    /// <param name="user"></param>
    /// <param name="email"></param>
    /// <returns></returns>
    public string getProwiseSSOUrl(string user, string email)
    {
        try
        {
            string token = createTimebasedToken(user);
            string prowiseSsoUrl;
   
            String url = "http://www.prowise.com/presenter/external/";
            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("emailadres", email);
            nvc.Add("username", user);
            nvc.Add("brinnummer", brinNr);
            nvc.Add("organisatieID", organisatieID);
            nvc.Add("timeBasedToken", token);

            WebClient client = new WebClient();
            byte[] data = client.UploadValues(url, nvc);
            string resJson = System.Text.Encoding.ASCII.GetString(data);

            JObject jsonObj = JObject.Parse(resJson);
            if (String.IsNullOrEmpty(prowiseSsoUrl = (string)jsonObj["loginURL"]))
            {
                throw new Exception("Prowise settings are not correct");
            }

            return prowiseSsoUrl;         
        }
        catch (Exception ex)
        {
            OmniaLogger.Log.Error("Getting Prowise SSO url failed: ", ex);
            return null;
        }

    }

}